namespace MultipleMonitorVideo
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.Linq;
    using Caliburn.Micro;
    using ViewModels;

    public class AppBootstrapper : Bootstrapper<ControlPanelViewModel>
    {
        private CompositionContainer container;

        public AppBootstrapper()
        {
            this.Start();
        }

        protected override void Configure()
        {
            this.container = new CompositionContainer();

            CompositionBatch batch = new CompositionBatch();

            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue<ControlPanelViewModel>(new ControlPanelViewModel());
            batch.AddExportedValue(this.container);

            this.container.Compose(batch);
        }

        // This GetInstance function fails to locate the right View for the ViewModel,
        // for some reason. Commenting out for now.
        protected override object GetInstance(Type service, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;
            IEnumerable<object> exports = this.container.GetExportedValues<object>(contract);

            if (exports.Any())
            {
                return exports.First();
            }

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return this.container.GetExportedValues<object>(AttributedModelServices.GetContractName(service));
        }

        protected override void BuildUp(object instance)
        {
            this.container.SatisfyImportsOnce(instance);
        }
    }
}